<?php
/**
 * @file
 * Download Monitor - Allows you to trace file downloads. Just place the direct link
 * to the file on the web, and specify the extensions of files you want to trace in the GUI.
 * It creates interactive chart and records downloads for today, yesterday, this week,
 * last week, this month, last month and total.
 * Requires writable .htaccess file of Apache Web server in Joomla root folder.
 * @package download-monitor
 * @version 1.0
 * @revision @REVISION@
 * @license http://www.gnu.org/licenses/gpl-3.0.txt     GNU General Public License v3
 * @copyright (C) 2012 by CodeGravity.com - All rights reserved!
 * @website http://www.codegravity.com
 */

ob_start();
defined('_JEXEC') or die('Restricted access'); ?>
<h1>
<?php
$db =& JFactory::getDBO();
$option = @$_REQUEST['option'];
$file = @$_REQUEST['file'];

$filepathquery = sprintf("SELECT * FROM #__download_monitor_paths where dname='%s'", mysql_escape_string($file));
$db->setQuery($filepathquery);
$filepathar= $db->loadRow();
$filepathid = $filepathar[0];

if($option=='com_download-monitor')
{
	if($file!='')
	{
		$currdate = date("Y-m-d");
		
		$filesearchquery = sprintf("SELECT COUNT(*) FROM #__download_monitor_paths where dname='%s'", mysql_escape_string($file));
		$db->setQuery($filesearchquery);
		$filesearchar = $db->loadResult();
		if($filesearchar>0)
		{
			$filepathquery_add = sprintf("insert into #__download_monitor_counter (did,ddate) values ('%s','%s')", (int)$filepathid, mysql_escape_string($currdate));
			$db->setQuery($filepathquery_add);
			$db->query();
		}
		else
		{
            $file_add = sprintf("insert into #__download_monitor_paths (dname) values ('%s')", mysql_escape_string($file));
            $db->setQuery($file_add);
            $db->query();

            $path_query = "select did from #__download_monitor_paths where dname = ('$file')";
            $db->setQuery($path_query);
            $db->query();
            $filepathid = $db->loadResult();


            $counter_add = sprintf("insert into #__download_monitor_counter (did,ddate) values ('%d','%s')", (int) $filepathid, mysql_escape_string($currdate));
			$db->setQuery($counter_add);
			$db->query();
			
		}
		$jp = str_replace("administrator","",JPATH_BASE);
		$filepath = $jp."/".trim($file);
		$file = basename($filepath);
		if (file_exists($filepath))
		{
		header("Content-Type: application/octet-stream");
		header("Content-Disposition: attachment; filename=".$file);
		header("Content-Transfer-Encoding: binary");
		ob_clean();    
		flush();       
		readfile($filepath);
		exit;
		}
	}
}
else
{
	echo "FILE NOT FOUND";
}

?>
</h1>